# -*- coding: utf-8 -*-
"""
根据API文档修正的服务器
"""
from flask import Flask, jsonify, request, render_template_string
from flask_cors import CORS
import requests
import json
from datetime import datetime, timedelta
import openai
import os
import sys

app = Flask(__name__)
CORS(app)

# API配置
DEEPSEEK_API_KEY = "sk-00d9e28b0be74eb4b070a062b7cb73b7"
DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1"
DEEPSEEK_MODEL = "deepseek-chat"
GAODE_API_KEY = "003df4ac18f1cca97eaf59dc90afbaa2"

# 聚合数据API配置
JUHE_FLIGHT_APPKEY = "b0daee5c7cf963ae6458020601583575"
JUHE_TRAIN_APPKEY = "5d11310f7cfa2c69ad50641bc3cf0288"

# 城市到IATA机场代码映射
CITY_TO_IATA = {
    '北京': 'BJS',
    '上海': 'SHA', 
    '广州': 'CAN',
    '深圳': 'SZX',
    '大连': 'DLC',
    '合肥': 'HFE',
    '南京': 'NKG',
    '杭州': 'HGH',
    '武汉': 'WUH',
    '成都': 'CTU',
    '重庆': 'CKG',
    '西安': 'SIA',
    '天津': 'TSN',
    '青岛': 'TAO',
    '沈阳': 'SHE',
    '哈尔滨': 'HRB',
    '厦门': 'XMN',
    '福州': 'FOC',
    '长沙': 'CSX',
    '郑州': 'CGO',
    '济南': 'TNA',
    '太原': 'TYN',
    '石家庄': 'SJW',
    '呼和浩特': 'HET',
    '兰州': 'LHW',
    '银川': 'INC',
    '西宁': 'XNN',
    '乌鲁木齐': 'URC',
    '拉萨': 'LXA',
    '昆明': 'KMG',
    '贵阳': 'KWE',
    '南宁': 'NNG',
    '海口': 'HAK',
    '三亚': 'SYX'
}

# 城市到12306车站名映射
CITY_TO_STATION = {
    '北京': '北京',
    '上海': '上海',
    '广州': '广州',
    '深圳': '深圳',
    '大连': '大连北',
    '合肥': '合肥南',
    '南京': '南京南',
    '杭州': '杭州东',
    '武汉': '武汉',
    '成都': '成都东',
    '重庆': '重庆北',
    '西安': '西安北',
    '天津': '天津',
    '青岛': '青岛',
    '沈阳': '沈阳',
    '哈尔滨': '哈尔滨西',
    '厦门': '厦门北',
    '福州': '福州',
    '长沙': '长沙南',
    '郑州': '郑州东',
    '济南': '济南西',
    '太原': '太原南',
    '石家庄': '石家庄',
    '呼和浩特': '呼和浩特',
    '兰州': '兰州西',
    '银川': '银川',
    '西宁': '西宁',
    '乌鲁木齐': '乌鲁木齐',
    '拉萨': '拉萨',
    '昆明': '昆明南',
    '贵阳': '贵阳北',
    '南宁': '南宁',
    '海口': '海口',
    '三亚': '三亚'
}

class CorrectedTravelAPI:
    def __init__(self):
        self.gaode_key = GAODE_API_KEY
        self.base_url = "https://restapi.amap.com/v3"
        
        # 初始化DeepSeek AI客户端
        try:
            if hasattr(openai, 'OpenAI'):
                self.ai_client = openai.OpenAI(
                    api_key=DEEPSEEK_API_KEY,
                    base_url=DEEPSEEK_BASE_URL
                )
                self.ai_available = True
                self.use_new_client = True
                print("✅ DeepSeek AI 客户端初始化成功")
            else:
                openai.api_key = DEEPSEEK_API_KEY
                openai.api_base = DEEPSEEK_BASE_URL
                self.ai_available = True
                self.use_new_client = False
                print("✅ DeepSeek AI 客户端初始化成功 (旧版本)")
        except Exception as e:
            print(f"❌ DeepSeek AI 客户端初始化失败: {e}")
            self.ai_available = False
    
    def get_flight_data(self, origin, destination, date=None):
        """获取机票数据 - 使用正确的API格式"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        print(f"🔍 获取机票数据: {origin} → {destination} ({date})")
        
        try:
            # 转换为IATA代码
            from_code = CITY_TO_IATA.get(origin, origin)
            to_code = CITY_TO_IATA.get(destination, destination)
            
            print(f"📍 机场代码: {from_code} → {to_code}")
            
            # 使用聚合数据API - 按照文档格式
            url = "https://apis.juhe.cn/flight/query"
            
            # 使用POST请求，Content-Type: application/x-www-form-urlencoded
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
            
            data = {
                'key': JUHE_FLIGHT_APPKEY,
                'dtype': 'json',
                'departure': from_code,  # 使用IATA代码
                'arrival': to_code,      # 使用IATA代码
                'departureDate': date    # 格式：2025-12-21
            }
            
            print(f"📡 机票API请求: {url}")
            print(f"📋 请求数据: {data}")
            
            response = requests.post(url, headers=headers, data=data, timeout=15)
            print(f"📊 响应状态: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print(f"📋 响应数据: {json.dumps(result, ensure_ascii=False)[:300]}...")
                
                if result.get('error_code') == 0:
                    flights = self._parse_flight_data(result, origin, destination)
                    print(f"✅ 获取到 {len(flights)} 条机票数据")
                    return flights
                else:
                    print(f"❌ 机票API错误: {result.get('reason', '未知')}")
                    print(f"错误代码: {result.get('error_code')}")
                    return []
            else:
                print(f"❌ 机票API请求失败: {response.status_code}")
                return []
                
        except Exception as e:
            print(f"❌ 机票API异常: {e}")
            return []
    
    def get_train_data(self, origin, destination, date=None):
        """获取火车票数据"""
        if not date:
            date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
        
        print(f"🔍 获取火车票数据: {origin} → {destination} ({date})")
        
        try:
            # 使用12306标准车站名
            from_station = CITY_TO_STATION.get(origin, origin)
            to_station = CITY_TO_STATION.get(destination, destination)
            
            print(f"📍 车站名: {from_station} → {to_station}")
            
            url = "https://apis.juhe.cn/fapigw/train/query"
            params = {
                'key': JUHE_TRAIN_APPKEY,
                'dtype': 'json',
                'from': from_station,
                'to': to_station,
                'date': date
            }
            
            print(f"📡 火车票API请求: {url}")
            print(f"📋 参数: {params}")
            
            response = requests.get(url, params=params, timeout=15)
            print(f"📊 响应状态: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print(f"📋 响应数据: {json.dumps(result, ensure_ascii=False)[:300]}...")
                
                if result.get('error_code') == 0:
                    trains = self._parse_train_data(result, origin, destination)
                    print(f"✅ 获取到 {len(trains)} 条火车票数据")
                    return trains
                else:
                    print(f"❌ 火车票API错误: {result.get('reason', '未知')}")
                    print(f"错误代码: {result.get('error_code')}")
                    return []
            else:
                print(f"❌ 火车票API请求失败: {response.status_code}")
                return []
                
        except Exception as e:
            print(f"❌ 火车票API异常: {e}")
            return []
    
    def _parse_flight_data(self, data, origin, destination):
        """解析机票数据"""
        flights = []
        
        try:
            result = data.get('result', {})
            flight_list = result.get('data', [])
            
            print(f"📊 解析航班数据，共 {len(flight_list)} 条")
            
            for item in flight_list:
                try:
                    flight = {
                        'type': 'flight',
                        'flight_number': item.get('flightNo', ''),
                        'airline': item.get('airlineName', ''),
                        'origin': origin,
                        'destination': destination,
                        'dep_time': item.get('departureTime', ''),
                        'arr_time': item.get('arrivalTime', ''),
                        'price': int(item.get('price', 0)),
                        'dep_airport': item.get('departureAirport', ''),
                        'arr_airport': item.get('arrivalAirport', ''),
                        'aircraft': item.get('aircraftType', ''),
                        'has_stop': '是' if item.get('stops', 0) > 0 else '否',
                        'is_transfer': '否',
                        'duration': item.get('duration', ''),
                        'source': '聚合数据API',
                        'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    }
                    
                    if flight['price'] > 0:
                        flights.append(flight)
                        print(f"  ✅ 解析到航班: {flight['flight_number']} - ¥{flight['price']}")
                        
                except Exception as e:
                    print(f"  ❌ 解析航班条目异常: {e}")
                    continue
            
        except Exception as e:
            print(f"❌ 机票数据解析异常: {e}")
        
        return flights
    
    def _parse_train_data(self, data, origin, destination):
        """解析火车票数据"""
        trains = []
        
        try:
            result = data.get('result', {})
            train_list = result.get('data', [])
            
            print(f"📊 解析火车数据，共 {len(train_list)} 条")
            
            for item in train_list:
                try:
                    train = {
                        'type': 'train',
                        'train_number': item.get('trainNo', ''),
                        'train_type': item.get('trainType', ''),
                        'origin': origin,
                        'destination': destination,
                        'dep_time': item.get('departureTime', ''),
                        'arr_time': item.get('arrivalTime', ''),
                        'price': int(item.get('price', 0)),
                        'dep_station': item.get('departureStation', ''),
                        'arr_station': item.get('arrivalStation', ''),
                        'duration': item.get('duration', ''),
                        'seat_type': item.get('seatType', ''),
                        'is_high_speed': '是' if 'G' in item.get('trainNo', '') or 'D' in item.get('trainNo', '') else '否',
                        'source': '聚合数据API',
                        'crawl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    }
                    
                    if train['price'] > 0:
                        trains.append(train)
                        print(f"  ✅ 解析到火车: {train['train_number']} - ¥{train['price']}")
                        
                except Exception as e:
                    print(f"  ❌ 解析火车条目异常: {e}")
                    continue
            
        except Exception as e:
            print(f"❌ 火车票数据解析异常: {e}")
        
        return trains

# 创建API实例
api = CorrectedTravelAPI()

@app.route('/')
def index():
    """主页"""
    return render_template_string(INDEX_TEMPLATE)

@app.route('/api/status')
def api_status():
    """API状态检查"""
    return jsonify({
        'status': 'success',
        'message': '修正版服务器运行正常',
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'features': [
            '真实机票数据获取（聚合数据API - 正确格式）',
            '真实火车票数据获取（聚合数据API）',
            '智能排序功能',
            'DeepSeek AI集成'
        ],
        'apis': {
            'flight': 'enabled',
            'train': 'enabled',
            'deepseek': 'enabled' if api.ai_available else 'disabled'
        },
        'supported_cities': list(CITY_TO_IATA.keys())
    })

@app.route('/api/search', methods=['POST'])
def search_travel():
    """搜索交通方式"""
    try:
        data = request.get_json()
        origin = data.get('origin', '')
        destination = data.get('destination', '')
        date = data.get('date', '')
        
        if not origin or not destination:
            return jsonify({'error': '请提供出发地和目的地'}), 400
        
        print(f"🔍 搜索请求: {origin} → {destination} ({date})")
        
        # 获取机票数据
        flights = api.get_flight_data(origin, destination, date)
        
        # 获取火车票数据
        trains = api.get_train_data(origin, destination, date)
        
        # 合并数据
        all_data = flights + trains
        
        # 按价格排序
        all_data.sort(key=lambda x: x.get('price', 0))
        
        result = {
            'status': 'success',
            'data': all_data,
            'total': len(all_data),
            'flights': len(flights),
            'trains': len(trains),
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        print(f"✅ 搜索完成: 找到 {len(all_data)} 条结果")
        return jsonify(result)
        
    except Exception as e:
        print(f"❌ 搜索异常: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/cities')
def get_cities():
    """获取支持的城市列表"""
    return jsonify({
        'status': 'success',
        'cities': list(CITY_TO_IATA.keys()),
        'total': len(CITY_TO_IATA)
    })

# HTML模板
INDEX_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能交通规划助手 - 修正版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        .search-section {
            padding: 30px;
            background: #f8f9fa;
        }
        
        .search-form {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 20px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        
        .form-group input, .form-group select {
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .search-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .search-btn:hover {
            transform: translateY(-2px);
        }
        
        .results-section {
            padding: 30px;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .results-count {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }
        
        .results-list {
            display: grid;
            gap: 15px;
        }
        
        .result-item {
            background: white;
            border: 2px solid #e1e5e9;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .result-item:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .result-type {
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .result-price {
            font-size: 1.5em;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .result-details {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .detail-item {
            text-align: center;
        }
        
        .detail-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }
        
        .detail-value {
            font-weight: bold;
            color: #333;
        }
        
        .result-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
            color: #666;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            font-size: 1.2em;
            color: #666;
        }
        
        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .success {
            background: #efe;
            color: #3c3;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .api-status {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 14px;
            z-index: 1000;
        }
        
        .city-hint {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        
        @media (max-width: 768px) {
            .search-form {
                grid-template-columns: 1fr;
            }
            
            .result-details {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="api-status" id="apiStatus">API连接正常</div>
    
    <div class="container">
        <div class="header">
            <h1>🚀 智能交通规划助手</h1>
            <p>基于聚合数据API的真实机票和火车票数据（修正版）</p>
        </div>
        
        <div class="search-section">
            <form class="search-form" id="searchForm">
                <div class="form-group">
                    <label for="origin">出发地</label>
                    <input type="text" id="origin" name="origin" placeholder="请输入出发城市" required>
                    <div class="city-hint">支持：北京、上海、广州、深圳、大连、合肥等</div>
                </div>
                <div class="form-group">
                    <label for="destination">目的地</label>
                    <input type="text" id="destination" name="destination" placeholder="请输入到达城市" required>
                    <div class="city-hint">支持：北京、上海、广州、深圳、大连、合肥等</div>
                </div>
                <div class="form-group">
                    <label for="date">出发日期</label>
                    <input type="date" id="date" name="date" required>
                </div>
                <button type="submit" class="search-btn">🔍 搜索</button>
            </form>
        </div>
        
        <div class="results-section">
            <div id="resultsContainer">
                <div class="loading" id="loadingMessage" style="display: none;">
                    🔍 正在搜索中，请稍候...
                </div>
                <div id="resultsContent"></div>
            </div>
        </div>
    </div>

    <script>
        // 设置默认日期为明天
        document.getElementById('date').value = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().split('T')[0];
        
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const origin = document.getElementById('origin').value;
            const destination = document.getElementById('destination').value;
            const date = document.getElementById('date').value;
            
            if (!origin || !destination) {
                alert('请填写出发地和目的地');
                return;
            }
            
            await searchTravel(origin, destination, date);
        });
        
        // 搜索交通方式
        async function searchTravel(origin, destination, date) {
            const loadingMessage = document.getElementById('loadingMessage');
            const resultsContent = document.getElementById('resultsContent');
            
            loadingMessage.style.display = 'block';
            resultsContent.innerHTML = '';
            
            try {
                const response = await fetch('/api/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        origin: origin,
                        destination: destination,
                        date: date
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    displayResults(data.data, data.total, data.flights, data.trains);
                } else {
                    showError(data.error || '搜索失败');
                }
            } catch (error) {
                showError('网络错误：' + error.message);
            } finally {
                loadingMessage.style.display = 'none';
            }
        }
        
        // 显示结果
        function displayResults(results, total, flights, trains) {
            if (results.length === 0) {
                resultsContent.innerHTML = '<div class="error">未找到相关交通信息</div>';
                return;
            }
            
            let html = `
                <div class="results-header">
                    <div class="results-count">找到 ${total} 条结果（航班 ${flights} 条，火车 ${trains} 条）</div>
                </div>
                <div class="results-list">
            `;
            
            results.forEach((item, index) => {
                const typeIcon = item.type === 'flight' ? '✈️' : '🚄';
                const typeName = item.type === 'flight' ? '航班' : '火车';
                const number = item.flight_number || item.train_number || '';
                const depTime = item.dep_time || '';
                const arrTime = item.arr_time || '';
                const duration = item.duration || '';
                const price = item.price || 0;
                
                html += `
                    <div class="result-item" onclick="selectResult(${index})">
                        <div class="result-header">
                            <div class="result-type">
                                <span>${typeIcon}</span>
                                <span>${typeName} ${number}</span>
                            </div>
                            <div class="result-price">¥${price}</div>
                        </div>
                        <div class="result-details">
                            <div class="detail-item">
                                <div class="detail-label">出发时间</div>
                                <div class="detail-value">${depTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">到达时间</div>
                                <div class="detail-value">${arrTime}</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">行程时间</div>
                                <div class="detail-value">${duration}</div>
                            </div>
                        </div>
                        <div class="result-meta">
                            <span>数据源：${item.source || '未知'}</span>
                            <span>更新时间：${item.crawl_time || ''}</span>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            resultsContent.innerHTML = html;
        }
        
        // 选择结果
        function selectResult(index) {
            const item = results[index];
            alert(`已选择：${item.type === 'flight' ? '航班' : '火车'} ${item.flight_number || item.train_number} - ¥${item.price}`);
        }
        
        // 显示错误
        function showError(message) {
            const resultsContent = document.getElementById('resultsContent');
            resultsContent.innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 检查API状态
        async function checkApiStatus() {
            try {
                const response = await fetch('/api/status');
                const data = await response.json();
                
                if (data.status === 'success') {
                    document.getElementById('apiStatus').textContent = 'API连接正常';
                    document.getElementById('apiStatus').style.background = '#4CAF50';
                } else {
                    document.getElementById('apiStatus').textContent = 'API连接异常';
                    document.getElementById('apiStatus').style.background = '#f44336';
                }
            } catch (error) {
                document.getElementById('apiStatus').textContent = 'API连接失败';
                document.getElementById('apiStatus').style.background = '#f44336';
            }
        }
        
        // 页面加载时检查API状态
        checkApiStatus();
        
        // 每30秒检查一次API状态
        setInterval(checkApiStatus, 30000);
    </script>
</body>
</html>
'''

if __name__ == '__main__':
    print("🚀 启动修正版服务器")
    print("=" * 60)
    print("🔧 根据API文档修正了调用格式")
    print("📡 使用POST请求，Content-Type: application/x-www-form-urlencoded")
    print("🏷️ 使用IATA机场代码（如BJS、SHA、CAN）")
    print("📅 使用正确日期格式（2025-12-21）")
    print("=" * 60)
    
    app.run(host='0.0.0.0', port=5002, debug=True)